package com.changzhi.controller;

import com.changzhi.common.util.Result;
import com.changzhi.ldyl.model.dto.ShareDto;
import com.changzhi.util.WxUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Description:第三方分享接口（比如微信）
 * @author: 小落
 * @date: 2021年07月12日
 */
@Slf4j
@CrossOrigin
@RequestMapping("share")
@RestController
public class ShareController {

	@Value("${wechat.appId}")
	private String wechatAppId;
	@Value("${wechat.secret}")
	private String wechatSecret;

	/**
	 * 分享到朋友圈
	 * @return
	 */
	@RequestMapping("/wechat")
	public Result getAccessTokenAndJsapi(@RequestBody ShareDto shareDto){
		String url = shareDto.getUrl();
		//log.info(" url = {} ",url);
		// 1. 获取access_token
		String accessToken = WxUtil.getAccessToken(wechatAppId, wechatSecret);
		//log.info(" accessToken = {} ",accessToken);
		// 2. 获取access_ticket
		String accessTicket = WxUtil.getAccessTicket(accessToken);
		//log.info(" accessTicket = {} ",accessTicket);
		// 3. 获取时间戳和随机字符串
		String nonceStr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);//随机字符串
		String timestamp = String.valueOf(System.currentTimeMillis() / 1000);//时间戳
		//log.info("nonceStr = {} ,  timestamp = {}",nonceStr,timestamp);
		// 4. 获取url
		if (StringUtils.isEmpty(url)){
			url = URLEncoder.encode(WxUtil.url);
		}
		// 5. 将参数排序并拼接字符串
		String str = "jsapi_ticket="+accessTicket+"&noncestr="+nonceStr+"&timestamp="+timestamp+"&url="+url;
		// 6. 将字符串进行sha1加密
		String signature = WxUtil.SHA1(str);
		Map<String,String> map=new HashMap();
		//公众号的唯一标识
		map.put("appId", wechatAppId);
		map.put("timestamp",timestamp);
		map.put("accessToken",accessToken);
		map.put("ticket",accessTicket);
		map.put("nonceStr",nonceStr);
		map.put("signature",signature);
		return Result.success(map);
	}

}
